# 设置工作目录
setwd("D:/1大学生活/大三下/zxy/R语言/class2")

#读取文件
clin_inf<-read.csv("clin_inf.csv",sep =" ",)
count<-read.csv("count.csv",sep=" ")
exp_inf<-read.csv("exp_inf.csv",sep=" ")
ID_annoation <- read.csv("ID_annoation.csv",sep=" ")


#合并
meta <- merge(clin_inf,exp_inf)
#修改行名
rownames(count) <- count$gene_id 
count <- count[,-1] 

install.packages("BiocManager")
BiocManager::install("Biobase")
library(BiocGenerics)
library(Biobase)

x <- colnames(count)
x <- gsub("(.*).$","\\1",x)
x <- gsub("X(...$)","PTB\\1",x)
x <- gsub("X","XYA",x)
colnames(count) <- x

#数据对齐
rownames(meta) <- meta$样本名称
meta <- meta[match(colnames(count),rownames(meta)),]

#简化ID，去除重复基因
#对齐表达矩阵
rownames(ID_annoation) <- ID_annoation$gene_id
ID_annoation$gene_id <- gsub("\\..*","",ID_annoation$gene_id)
pos2 <- duplicated(ID_annoation$gene_id)
ID_annoation2 <- ID_annoation[ID_annoation$gene_id %in% ID_annoation$gene_id[pos2], ] 
ID_annoation <- ID_annoation[!duplicated(ID_annoation$gene_id), ]
rownames(ID_annoation) <- ID_annoation$gene_id
ID_annoation <- ID_annoation[match(rownames(count), rownames(ID_annoation)), ]

#ExpressionSet
eset <- ExpressionSet(
  assayData = as.matrix(count),
  phenoData = new("AnnotatedDataFrame", data = meta),
  featureData = new("AnnotatedDataFrame", data = ID_annoation)
)
#提取/删选部分基因
eset2 <- eset[1:10, 1:10]
treated_samples <- eset[, eset$批次 == "batch1"]
chrX_genes <- eset[fData(eset)$seqnames == "chr1", ]
